package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"net/http"
	"io"
	"flag"
	yaml "gopkg.in/yaml.v2"
)

type TarList struct {
	Tar struct {
		Name    string `yaml:"local-name"`
		Uri     string `yaml:"uri"`
		Version string `yaml:"version"`
	}
}

func main() {
	args := os.Args
	help := flag.Bool("h",false,args[0]+"help")
	decompress := flag.Bool("x",false,"decompress src tars")
	download := flag.Bool("d",false,"download src tars")
	flag.Parse()

	installFile:=flag.Args()
	if *help || (!*decompress && !*download){
		fmt.Println(args[0]," [-x | -d] <rosinstall_file>")
		return
	}

	//parse rosinstall file
	tarList := make([]TarList, 0)
	content, err := ioutil.ReadFile(installFile[0])
	if err != nil {
		fmt.Printf("read file(%v) error: %v\n", installFile,err)
	}
	err = yaml.Unmarshal([]byte(content), &tarList)
	if err != nil {
		fmt.Printf("unmarshal error: %v\n", err)
	}

	for _, t := range tarList {
		_, file := path.Split(t.Tar.Name)
		filePath := "src/"+file+".tar.gz"
		srcDir := "src/"+t.Tar.Name

		//下载
		if *download {
			f, err := os.Create(filePath)
			if err != nil {
				panic(err)
			}
			fmt.Printf("download start: %s --> %s\n",filePath,t.Tar.Uri)
			res, err := http.Get(t.Tar.Uri)
			if err != nil {
				panic(err)
			}
			io.Copy(f, res.Body)
			fmt.Printf("download finshed: %s\n",filePath)
		}

		//解压
		if *decompress {
			err = os.MkdirAll(srcDir, os.ModePerm)
			if err != nil {
				panic(err)
			}
			cmd := exec.Command("tar", "zxvf", filePath, "-C", srcDir, "--strip-components", "1")
			err = cmd.Run()
			if err != nil {
				log.Fatalf("==>[%s]  -->Error:%s\n", cmd.String(), err)
			}else{
				fmt.Printf("==>[%s]  -->OK\n", cmd.String())
			}
		}
	}

}
